package com.lightbook.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lightbook.pojo.Book;
import com.lightbook.pojo.Cart;
import com.lightbook.service.BookService;
import com.lightbook.service.CartService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 购买图书
 * 主页点击购买图书的时候将书id存储到数据库中
 */
@Controller
public class ShoppingCartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private BookService bookService;

    // 购买书籍的接口
    @ResponseBody
    @GetMapping("/insert/cart/{bookName}/price/{bookPrice}")
    public Boolean InsertCart(@PathVariable String bookName,
                              @PathVariable Double bookPrice,
                              @CookieValue String userEmail) {

        Integer cartCount = 1;  // 购买的书的数量
        double cartTotalPrice = 0;
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper();
        cartQueryWrapper.eq("book_name", bookName);
        cartQueryWrapper.eq("user_email", userEmail);

        List<Cart> list = cartService.list(cartQueryWrapper);
        if (list.size() > 0) {
            Cart cart1 = list.get(0);
            cartCount = cart1.getCartCount();
            cartCount++;
        }

        cartTotalPrice = bookPrice * cartCount;

        Cart cart2 = new Cart();
        cart2.setBookName(bookName);
        cart2.setCartCount(cartCount);
        cart2.setCartPrice(bookPrice);
        cart2.setCartTotalPrice(cartTotalPrice);
        cart2.setUserEmail(userEmail);

        boolean flag = cartService.saveOrUpdate(cart2, cartQueryWrapper);

        if (flag) {// 买完书之后, 销量++, 库存--
            QueryWrapper<Book> bookQueryWrapper = new QueryWrapper<>();
            bookQueryWrapper.eq("book_name", bookName); // 先查询出当前这本书
            List<Book> bookList = bookService.list(bookQueryWrapper);
            if (bookList.size() > 0) {
                Book book = bookList.get(0);
                Integer oldBookSales = book.getBookSales();
                Integer oldBookStock = book.getBookStock();
                book.setBookSales(oldBookSales+1);
                book.setBookStock(oldBookStock-1);
                bookService.update(book, bookQueryWrapper);
            }
        }

        return flag;
    }
}
